// 发货单路由处理函数文件
// 该文件包含了发货单相关API的具体实现逻辑

const { sequelize } = require('../db/index');
const initModels = require('../models/init-models');

// 初始化模型
const models = initModels(sequelize, require('sequelize').DataTypes);
const DeliveryOrders = models.delivery_orders;
const SalesOrders = models.sales_orders;

/**
 * 获取发货单列表
 * @param {Request} req - 请求对象
 * @param {Response} res - 响应对象
 */
async function getDeliveryOrders(req, res) {
  try {
    // 从查询参数获取分页和筛选条件
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    const offset = (page - 1) * pageSize;
    
    // 构建查询条件
    const whereConditions = {};
    
    // 如果有发货单编号筛选条件
    if (req.query.deliveryNumber) {
      whereConditions.delivery_number = {
        [require('sequelize').Op.like]: `%${req.query.deliveryNumber}%`
      };
    }
    
    // 如果有快递公司名称筛选条件
    if (req.query.courierName) {
      whereConditions.courier_name = {
        [require('sequelize').Op.like]: `%${req.query.courierName}%`
      };
    }
    
    // 如果有状态筛选条件
    if (req.query.status) {
      whereConditions.status = req.query.status;
    }
    
    // 查询发货单列表，包含关联的销售订单
    const result = await DeliveryOrders.findAndCountAll({
      where: whereConditions,
      include: [{
        model: SalesOrders,
        as: 'sales_orders',
        attributes: ['order_id', 'order_number', 'customer_id', 'product_id', 'quantity', 'total_amount', 'status']
      }],
      order: [['delivery_date', 'DESC']],
      limit: pageSize,
      offset: offset
    });
    
    // 返回成功响应
    res.success({
      deliveryOrders: result.rows,
      pagination: {
        totalCount: result.count,
        currentPage: page,
        pageSize: pageSize
      }
    }, '获取发货单列表成功');
  } catch (err) {
    // 返回错误响应
    res.error('获取发货单列表失败');
  }
}

/**
 * 根据ID获取发货单详情
 * @param {Request} req - 请求对象
 * @param {Response} res - 响应对象
 */
async function getDeliveryOrderById(req, res) {
  try {
    // 从请求参数获取ID
    const { id } = req.params;
    
    // 查找发货单详情，包含关联的销售订单
    const deliveryOrder = await DeliveryOrders.findByPk(id, {
      include: [{
        model: SalesOrders,
        as: 'sales_orders',
        attributes: ['order_id', 'order_number', 'customer_id', 'product_id', 'quantity', 'total_amount', 'status']
      }]
    });
    
    if (!deliveryOrder) {
      return res.error('发货单不存在', 1, 404);
    }
    
    // 返回成功响应
    res.success(deliveryOrder, '获取发货单详情成功');
  } catch (err) {
    // 返回错误响应
    res.error('获取发货单详情失败');
  }
}

/**
 * 添加新的发货单
 * @param {Request} req - 请求对象
 * @param {Response} res - 响应对象
 */
async function addDeliveryOrder(req, res) {
  const transaction = await sequelize.transaction();
  try {
    // 从请求体获取数据
    const { 
      delivery_date, 
      courier_id, 
      courier_name, 
      tracking_number, 
      delivered_by, 
      notes,
      order_ids 
    } = req.body;
    
    // 生成发货单编号（格式：FH+日期+4位序号）
    const date = new Date();
    const dateString = date.toISOString().slice(0, 10).replace(/-/g, '');
    const lastOrder = await DeliveryOrders.findOne({
      where: {
        delivery_number: {
          [require('sequelize').Op.like]: `FH${dateString}%`
        }
      },
      order: [['delivery_number', 'DESC']]
    });
    
    let sequenceNumber = 1;
    if (lastOrder) {
      const lastSequence = parseInt(lastOrder.delivery_number.slice(-4));
      sequenceNumber = lastSequence + 1;
    }
    
    const deliveryNumber = `FH${dateString}${sequenceNumber.toString().padStart(4, '0')}`;
    
    // 创建新的发货单记录
    const newDeliveryOrder = await DeliveryOrders.create({
      delivery_number: deliveryNumber,
      delivery_date,
      courier_id,
      courier_name,
      tracking_number,
      delivered_by,
      notes,
      status: 1 // 默认状态为待发货
    }, { transaction });
    
    // 如果有订单ID列表，关联这些订单到发货单
    if (order_ids && Array.isArray(order_ids) && order_ids.length > 0) {
      // 更新销售订单的delivery_id字段
      await SalesOrders.update(
        { delivery_id: newDeliveryOrder.delivery_id },
        { 
          where: { 
            order_id: { 
              [require('sequelize').Op.in]: order_ids 
            } 
          },
          transaction 
        }
      );
    }
    
    // 提交事务
    await transaction.commit();
    
    // 重新查询发货单详情，包含关联的销售订单
    const deliveryOrderWithOrders = await DeliveryOrders.findByPk(newDeliveryOrder.delivery_id, {
      include: [{
        model: SalesOrders,
        as: 'sales_orders',
        attributes: ['order_id', 'order_number', 'customer_id', 'product_id', 'quantity', 'total_amount', 'status']
      }]
    });
    
    // 返回成功响应
    res.success(deliveryOrderWithOrders, '添加发货单成功');
  } catch (err) {
    // 回滚事务
    await transaction.rollback();
    // 返回错误响应
    res.error('添加发货单失败');
  }
}

/**
 * 更新发货单信息
 * @param {Request} req - 请求对象
 * @param {Response} res - 响应对象
 */
async function updateDeliveryOrder(req, res) {
  const transaction = await sequelize.transaction();
  try {
    // 从请求体获取数据
    const { 
      delivery_id,
      delivery_date, 
      courier_id, 
      courier_name, 
      tracking_number, 
      delivered_by, 
      notes,
      order_ids 
    } = req.body;
    
    // 查找要更新的发货单
    const deliveryOrder = await DeliveryOrders.findByPk(delivery_id, { transaction });
    
    if (!deliveryOrder) {
      await transaction.rollback();
      return res.error('发货单不存在', 1, 404);
    }
    
    // 更新发货单信息
    await deliveryOrder.update({
      delivery_date: delivery_date || deliveryOrder.delivery_date,
      courier_id: courier_id || deliveryOrder.courier_id,
      courier_name: courier_name || deliveryOrder.courier_name,
      tracking_number: tracking_number || deliveryOrder.tracking_number,
      delivered_by: delivered_by || deliveryOrder.delivered_by,
      notes: notes || deliveryOrder.notes
    }, { transaction });
    
    // 如果有订单ID列表，更新订单与发货单的关联关系
    if (order_ids && Array.isArray(order_ids)) {
      // 先将当前关联到此发货单的所有订单的delivery_id设为null
      await SalesOrders.update(
        { delivery_id: null },
        { 
          where: { delivery_id: delivery_id },
          transaction 
        }
      );
      
      // 如果有新的订单ID列表，关联这些订单到发货单
      if (order_ids.length > 0) {
        await SalesOrders.update(
          { delivery_id: delivery_id },
          { 
            where: { 
              order_id: { 
                [require('sequelize').Op.in]: order_ids 
              } 
            },
            transaction 
          }
        );
      }
    }
    
    // 提交事务
    await transaction.commit();
    
    // 重新查询发货单详情，包含关联的销售订单
    const deliveryOrderWithOrders = await DeliveryOrders.findByPk(delivery_id, {
      include: [{
        model: SalesOrders,
        as: 'sales_orders',
        attributes: ['order_id', 'order_number', 'customer_id', 'product_id', 'quantity', 'total_amount', 'status']
      }]
    });
    
    // 返回成功响应
    res.success(deliveryOrderWithOrders, '更新发货单成功');
  } catch (err) {
    // 回滚事务
    await transaction.rollback();
    // 返回错误响应
    res.error('更新发货单失败');
  }
}

/**
 * 删除发货单
 * @param {Request} req - 请求对象
 * @param {Response} res - 响应对象
 */
async function deleteDeliveryOrder(req, res) {
  const transaction = await sequelize.transaction();
  try {
    // 从请求参数获取ID
    const { id } = req.params;
    
    // 查找要删除的发货单
    const deliveryOrder = await DeliveryOrders.findByPk(id, { transaction });
    
    if (!deliveryOrder) {
      await transaction.rollback();
      return res.error('发货单不存在', 1, 404);
    }
    
    // 将关联到此发货单的订单的delivery_id设为null
    await SalesOrders.update(
      { delivery_id: null },
      { 
        where: { delivery_id: id },
        transaction 
      }
    );
    
    // 删除发货单记录
    await deliveryOrder.destroy({ transaction });
    
    // 提交事务
    await transaction.commit();
    
    // 返回成功响应
    res.success(null, '删除发货单成功');
  } catch (err) {
    // 回滚事务
    await transaction.rollback();
    // 返回错误响应
    res.error('删除发货单失败');
  }
}

// 导出处理函数
module.exports = {
  getDeliveryOrders,
  getDeliveryOrderById,
  addDeliveryOrder,
  updateDeliveryOrder,
  deleteDeliveryOrder
};